package com.example.demo.controller.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
public class RedisClusterController {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;


        @GetMapping("/cluster/{key}/{value}")
        public void setRedis(@PathVariable("key")String key,@PathVariable("value")String value){

            redisTemplate.opsForValue().set(key,value);


        }

        @GetMapping("/cluster/{key}")
        public void getRedis(@PathVariable("key")String key){
            System.out.println(redisTemplate.opsForValue().get(key));
        }




    /** 释放锁lua脚本 */
    private static final String RELEASE_LOCK_LUA_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
    private static final String lockKey = "secKill_Lock";
    private static final String userId = "123456";
    private static final Long  OUT_TIME = 500L;
    public void TryGetLock() {








        String lockKey = "123";
        String UUID = "uuid";
        boolean success = redisTemplate.opsForValue().setIfAbsent(lockKey,UUID,3, TimeUnit.MINUTES);
        if (!success){
            System.out.println("锁已存在");
        }
        // 指定 lua 脚本，并且指定返回值类型
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_LUA_SCRIPT,Long.class);
        // 参数一：redisScript，参数二：key列表，参数三：arg（可多个）
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),UUID);
        System.out.println(result);
    }



}
